package com.hserver.docker.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.hserver.docker.bean.Deploy;
import com.hserver.docker.dao.DeployMapper;
import com.hserver.docker.service.DeployService;
import top.hserver.core.interfaces.HttpRequest;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.Bean;
import top.hserver.core.server.context.ConstConfig;

import java.util.List;

/**
 * @author yiChenLove
 */
@Bean
public class DeployServiceImpl implements DeployService {

    @Autowired
    private DeployMapper deployMapper;

    @Override
    public void updateContainerId(String uuid, String containerId) {
        Deploy detail = deployMapper.getDetail(uuid);
        if (detail != null) {
            detail.setContainerId(containerId);
        }
        deployMapper.updateById(detail);
    }

    @Override
    public Deploy getDeploy(String uuid) {
        return deployMapper.getDetail(uuid);
    }

    @Override
    public List<Deploy> getList() {
        return deployMapper.all();
    }

    @Override
    public List<Deploy> getProjectList(String name) {
        return deployMapper.getProjectList(name);
    }

    @Override
    public void insert(Deploy deploy) {
        deployMapper.insert(deploy);
    }

    @Override
    public void update(Deploy deploy) {
        deployMapper.updateById(deploy);
    }


    @Override
    public void del(String uuid) {
        deployMapper.deleteById(uuid);
    }

    @Override
    public boolean checkSource(HttpRequest request, String uuid) {
        String header = request.getHeader("User-Agent");
        if (header != null && header.trim().length() > 0) {
            Deploy deploy = getDeploy(uuid);
            if (deploy != null) {
                try {
                    JsonNode jsonNode = ConstConfig.JSON.readTree(request.getRawData());
                    JsonNode ref = jsonNode.get("ref");
                    if (ref != null) {
                        String s = ref.asText();
                        if (s != null && s.trim().length() > 0) {
                            if (s.contains(deploy.getBranch())) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
                } catch (JsonProcessingException ignored) {
                }
            } else {
                return false;
            }
        }
        return true;
    }
}
